package cn.com.niit.order.controller;

import cn.com.niit.order.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author YongMeng
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping(value = "/buy/{id}", method = RequestMethod.GET)
    public Product findById(@PathVariable Long id) {
        //远程调用，缺点是耦合度太高了，product发了变化，order要随之应对改变，硬编码的问题
        //Product product = restTemplate.getForObject("http://127.0.0.1:9011/product/" + id, Product.class);
        Product product = null;
        //根据服务的名称获取服务元数据信息列表
        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("service-product");
        //获取元数据信息，拼接成url
        ServiceInstance serviceInstance = serviceInstanceList.get(0);
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        String url = "http://"+host+":"+port+"/product/" + id;
        //远程调用
        product = restTemplate.getForObject(url, Product.class);
        //返回
        return product;
    }
}
